const handler = require('sv-handle-res')
const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
  // 题库列表
  async libList() {
    const {
      profession,
      lib_id
    } = this.params

    let libRes

    // 可根据所属的职业:profession_id筛选
    if (profession || lib_id) {
      libRes = await db.collection('st-exam-libs').where(dbCmd.or({
        "profession": dbCmd.eq(profession)
      }, {
        "lib_id": dbCmd.eq(lib_id)
      })).orderBy('sort', 'asc').get()
    } else {
      libRes = await db.collection('st-exam-libs').orderBy('sort', 'asc').get()
    }

    return handler.result({
      data: libRes.data,
    })
  },
  // 更新题库
  async libUpdate() {
    const {
      _id,
      lib_id,
      lib_name
    } = this.params

    if (!lib_id || !lib_name) {
      throw handler.result({
        code: 40001
      })
    }

    delete this.params._id // 移除_id字段，_id不参与更新
    const libRes = await db.collection('st-exam-libs').doc(_id).update(this.params)

    return handler.result({
      data: libRes,
    })
  },
  // 添加题库
  async libAdd() {
    const {
      lib_id,
      lib_name
    } = this.params

    if (!lib_id || !lib_name) {
      throw handler.result({
        code: 40001
      })
    }

    const libRes = await db.collection('st-exam-libs').add(this.params)

    return handler.result({
      data: libRes,
    })
  },
  // 删除题库
  async libDelete() {
    const {
      lib_id
    } = this.params

    if (!lib_id) {
      throw handler.result({
        code: 40001
      })
    }

    const libRes = await db.collection('st-exam-libs').where({
      "lib_id": dbCmd.eq(lib_id)
    }).remove()

    return handler.result({
      data: libRes,
    })
  },
}